<template>
    <div class="upload">
        <template v-if="isUploading">
            <div class="isUpload">
                <div class="bottom">
                    <div class="total">
                        上传进度：{{totalLoaded}}M/{{totalSize}}M
                    </div>
                    <div class="fail" v-if="isFail">
                        上传失败
                    </div>
                </div>
                <div class="main">
                    <div class="totalBar">
                        <p class="speed"
                           :style="{width: speedWidth, backgroundColor: isFail ? '#FB3500' : '#5d83ff',}"></p>
                    </div>
                    <div class="pre">
                        {{speedWidth}}
                    </div>
                    <div @click="handleCancel" class="cancel">
                        取消上传
                    </div>
                    <div @click="handleAgain" class="cancel" v-if="isFail">
                        重新上传
                    </div>
                </div>
            </div>
        </template>
        <template v-else>
            <input class="upload-input" type="file" accept="video/mp4, .mov,.mkv, .mpeg,.mp4, video/WebM,  video/mpeg"
                   @change="getFile($event)" ref="upload">
            <div class="showImg">
                <img class="articleCover" :src="articleCover" alt="" v-if="articleCover">
                <div class="upload-btn" v-else>
                    <img id="upload" src="@assets/upload.png" class="upload-img"/>
                    <span>点击上传视频</span>
                </div>
            </div>
        </template>
        <div class="tips" v-if="errorText">
            {{errorText}}
        </div>
    </div>
</template>

<script>
    import * as qiniu from 'qiniu-js'
    
    export default {
        name: "articleCover",
        data() {
            return {
                isUploading: false,
                articleCover: this.pageVideo.articleCover,
                file: '',
                videoUrl: this.pageVideo.videoUrl,
                errorText: '',
                qnToken: '',
                speedWidth: '0',
                totalSize: 0,
                totalLoaded: 0,
                subscription: null, //
                isFail: false,
            }
        },
        props: {
            pageVideo: Object
        },
        watch: {
            pageVideo(newValue) {
                this.articleCover = newValue.articleCover
                this.videoUrl = newValue.videoUrl
            }
        },
        
        methods: {
            //获取本地文件
            getFile(event) {
                this.file = event.target.files[0]
                this.submitForm(event)
            },
            //处理本地文件
            submitForm(event) {
                event.preventDefault()
                // let type = this.file.type //文件的类型
                let size = this.file.size //文件的大小
                let self = this
                // if (size > 10485760) {
                //     alert('请选择10M以内的图片！')
                //     return false
                // }
                
                // 获取 window 的 URL 工具
                var URL = window.URL || window.webkitURL
                // 通过 file 生成目标 url
                let imgURL = URL.createObjectURL(this.file)
                // var video = document.createElement('video')
                // video.src = imgURL
                // video.load() // fetches metadata
                var video = new Audio(imgURL)//audio也可获取视频的时长
                
                video.onloadedmetadata = evt => {
                    // Revoke when you don't need the url any more to release any reference
                    console.log(video.duration)
                    if (!video.duration && video.duration !== 0) {
                        alert('不支持该视频格式')
                        return
                    } else {
                        if (video.duration > 300) {
                            self.$refs.upload.value = ''
                            alert("上传视频时长小于5分钟")
                            return
                        } else {
                            this.uploadFile()
                        }
                    }
                }
            },
            async getQnToken(fileName) {
                await this.$axios({actionName: 'qn.token', fileName}).then(res => {
                    this.qnToken = res.data
                })
            },
            //提交
            async uploadFile() {
                this.isUploading = true
                
                let name = Math.random().toString(16).substr(2, 6).toUpperCase() + new Date().getTime() + '.mp4'
                await this.getQnToken(name)
                
                let self = this
                let file = this.file
                let token = this.qnToken
                let putExtra = {}
                let config = {
                    useCdnDomain: true,
                    region: qiniu.region.z0
                }
                
                let observable = qiniu.upload(file, name, token, putExtra, config)
                let observer = {
                    next(res) {//接收上传进度
                        self.speedWidth = (res.total.percent).toFixed(2) + '%'
                        self.totalSize = (res.total.size / 1024 / 1024).toFixed(1)
                        self.totalLoaded = (res.total.loaded / 1024 / 1024).toFixed(1)
                    },
                    error(err) {//
                        self.isFail = true
                    },
                    complete(res) {
                        self.articleCover = 'https://yun.linkwinning.com/' + name + '?vframe/jpg/offset/3'
                        self.isUploading = false
                        self.videoUrl = 'https://yun.linkwinning.com/' + name + '?1'
                        self.speedWidth = 0
                        self.totalSize = 0
                        self.totalLoaded = 0
                        self.$nextTick(() => {
                            self.$refs.upload.value = ''
                        })
                        
                        let obj = {
                            videoUrl: self.videoUrl,
                            articleCover: 'https://yun.linkwinning.com/' + name + '?vframe/jpg/offset/2',
                            videoWidth: res.width,
                            videoHeight: res.height,
                            articleCoverWidth: res.width,
                            articleCoverHeight: res.height,
                            videoTime: parseInt(res.duration),
                        }
                        self.$emit('uploadFile', obj)
                    }
                }
                var subscription = observable.subscribe(observer) // 上传开始
                this.subscription = subscription
                // subscription.unsubscribe()
            },
            handleCancel() {
                this.subscription.unsubscribe() // 上传取消
                this.isUploading = false
                this.speedWidth = 0
                this.totalSize = 0
                this.totalLoaded = 0
                this.isFail = false
                this.$nextTick(() => {
                    this.$refs.upload.value = ''
                })
            },
            handleAgain() {
                this.speedWidth = 0
                this.totalSize = 0
                this.totalLoaded = 0
                this.isFail = false
                this.uploadFile()
            }
        }
    }
</script>

<style lang="less" scoped>
    
    
    .upload {
        position: relative;
        margin-left: 20px;
        border-radius: 4px;
        cursor: pointer;
        
        &::before {
            position: absolute;
            top: 18px;
            left: -20px;
            content: '';
            display: block;
            width: 4px;
            height: 4px;
            border-radius: 50%;
            background: rgba(250, 100, 0, 1);
        }
        
        .isUpload {
            display: block;
            padding-bottom: 20px;
            width: 100%;
            height: 100%;
            
            .bottom {
                .flexed(start);
                
                .total {
                    font-size: 14px;
                    font-weight: 500;
                    color: rgba(0, 0, 0, 0.65);
                }
                
                .fail {
                    margin-left: 200px;
                    color: #FB3500;
                    font-size: 14px;
                }
            }
            
            .main {
                width: 100%;
                height: 100%;
                .flexed(start);
                margin-top: 15px;
                
                .totalBar {
                    position: relative;
                    width: 400px;
                    height: 8px;
                    border-radius: 4px;
                    background-color: rgba(0, 0, 0, 0.04);
                    overflow: hidden;
                    
                    .speed {
                        position: absolute;
                        top: 0;
                        left: 0;
                        height: 8px;
                    }
                }
                
                .pre {
                    color: rgba(93, 131, 255, .85);
                    margin-left: 8px;
                }
                
                .cancel {
                    margin-left: 23px;
                    font-weight: 800;
                    color: rgba(0, 0, 0, .65);
                }
            }
            
        }
        
        .showImg {
            width: 260px;
            height: 195px;
            overflow: hidden;
            border-radius: 4px;
            background: rgba(0, 0, 0, .04);
            
            .articleCover {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
            
            .upload-btn {
                padding-top: 68px;
                
                img {
                    display: block;
                    width: 34px;
                    height: auto;
                    margin: 0 auto 16px;
                }
                
                span {
                    display: block;
                    font-size: 12px;
                    font-weight: 400;
                    color: rgba(0, 0, 0, .4);
                    line-height: 17px;
                    text-align: center;
                }
            }
        }
        
        .upload-input {
            position: absolute;
            width: 260px;
            height: 195px;
            opacity: 0;
            cursor: pointer;
        }
        
        .tips {
            position: absolute;
            bottom: 5px;
            left: 300px;
            width: 300px;
            font-size: 12px;
            font-weight: bold;
            color: rgba(224, 32, 32, 1);
            line-height: 17px;
        }
    }
</style>
